/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.service.datasource.mybatis.mapper;

import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import yhao.infra.service.datasource.BaseDao;

import java.lang.reflect.Proxy;

import static org.springframework.util.Assert.notNull;

/**
 * automapper组件 dao的映射bean
 *
 * @see AutoMapper
 * @author yoara
 */
public class AutoMapperBean<T> implements InitializingBean,FactoryBean<T> {
    public static final String PROPERTY_MAPPER_INTERFACE = "mapperInterface";
    public static final String PROPERTY_BASE_DAO = "baseDao";
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Class<T> mapperInterface;
    private BaseDao baseDao;

    /**
     * {@inheritDoc}
     */
    @Override
    public T getObject(){
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(),
                new Class[] { mapperInterface },
                new AutoMapper<>(baseDao,mapperInterface));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Class<T> getObjectType() {
        return this.mapperInterface;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isSingleton() {
        return true;
    }

    public void setMapperInterface(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    @Autowired
    public void setBaseDao(BaseDao baseDao) {
        this.baseDao = baseDao;
    }

    @Override
    public void afterPropertiesSet(){
        notNull(this.mapperInterface, "Property 'mapperInterface' is required");
        notNull(this.baseDao, "Property 'baseDao' is required");
        if(baseDao.getSqlSession()!=null){
            Configuration configuration = baseDao.getSqlSession().getConfiguration();
            if (configuration!=null&&!configuration.hasMapper(this.mapperInterface)) {
                try {
                    configuration.addMapper(this.mapperInterface);
                } catch (Exception e) {
                    logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);
                    throw new IllegalArgumentException(e);
                } finally {
                    ErrorContext.instance().reset();
                }
            }
        }
    }
}
